package spring.cloud.tasks.executor.name_space.executor.task.task_listener.trigger_task_execute;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import spring.cloud.tasks.common.node.ExecutorNodePath;
import spring.cloud.tasks.executor.name_space.executor.task.task_listener.TreeCacheListener;
import spring.cloud.tasks.executor.utils.LogUtils;

/**
 * runOneTime operation.<br>
 * once triggered, delete the node.
 */
@Slf4j
@Setter
@Getter
class TriggerTaskRunAtOnceListener extends TreeCacheListener {

    private final TriggerTaskExecuteListenerHolder taskExecuteListenerHolder;

    public TriggerTaskRunAtOnceListener(TriggerTaskExecuteListenerHolder taskExecuteListener) {
        this.taskExecuteListenerHolder = taskExecuteListener;
    }

    @Override
    protected void dataChanged(final CuratorFramework curatorFramework, final String path, final TreeCacheEvent treeCacheEvent) {
        if (taskExecuteListenerHolder.isShutdown) {
            return;
        }
        if ((TreeCacheEvent.Type.NODE_ADDED == treeCacheEvent.getType() || TreeCacheEvent.Type.NODE_UPDATED == treeCacheEvent.getType()) && ExecutorNodePath.isRunOneTimePath(taskExecuteListenerHolder.taskId, path, taskExecuteListenerHolder.executorId)) {
            if (!taskExecuteListenerHolder.taskExecutor.getTaskExecuteEngine().isRunning()) {

                LogUtils.info(log, taskExecuteListenerHolder.taskId, "job run-at-once triggered, triggeredData:{}");
                taskExecuteListenerHolder.taskExecutor.rightNowExecute();
            } else {
                LogUtils.info(log, taskExecuteListenerHolder.taskId, "job is running, run-at-once ignored.");
            }
            try {
                taskExecuteListenerHolder.nameSpaceDataManager.delete(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
